import { useUserStore } from "@/stores/user"
import agentWhite from "./agent-white"
import pagesWhite from "./pages-white"

export type openWinType = 'navigateTo' | 'redirectTo' | 'reLaunch' | 'switchTab'

/**
 * 显示提示信息
 * @param message 
 * @param options 
 */
export const toast = (message: string, options?: any) => {
	uni.showToast({
		title: message,
		icon: 'none',
		...options
	})
}

/**
 * 打开新页面
 * @param params 
 * @param type 
 */
export const openWin = (params: UniApp.NavigateToOptions | UniApp.RedirectToOptions | UniApp.ReLaunchOptions | UniApp.SwitchTabOptions, type: openWinType = 'navigateTo') => {
	if (!params?.url) {
		uni.showToast({
			title: '缺少跳转地址',
			icon: 'none'
		})
		return
	}
	// 页面类型
	const pageType = params.url.split('?')[0]
	// 帮助中心
	if (pageType === '#help') {
		uni.navigateTo({
			url: `/pages/webview/index?type=help`
		})
		return
	}
	// 单页系统
	if (pageType === '#tags') {
		const tagName = params.url.split('?')[1]
		uni.navigateTo({
			url: `/pages/webview/index?type=tags&${tagName}`
		})
		return
	}
	// 检测是否白名单并登录
	const path = params.url.split('?')[0]
	const token = uni.getStorageSync('token')
	if (!pagesWhite.includes(path) && !token) {
		// 重定向到登录页
		uni.navigateTo({
			url: `/pages/login/index`
		})
		return;
		// uni.navigateTo({
		// 	url: `/pages/login/index?redirect=${params.url}`
		// })
		// return;
	}
	// 检测是否代理
	const user = storeToRefs(useUserStore()).userInfo
	if (agentWhite.includes(path) && !user.value.is_dealer) {
		// 重定向到代理申请
		uni.navigateTo({
			url: `/pages/users/dealer/apply/index`
		})
		return;
	}
	switch (type) {
		case 'navigateTo':
			uni.navigateTo(params)
			break;
		case 'redirectTo':
			uni.redirectTo(params)
			break;
		case 'reLaunch':
			uni.reLaunch(params)
			break;
		case 'switchTab':
			uni.switchTab(params)
			break;
		default:
			uni.showToast({
				title: '跳转方式错误',
				icon: 'none'
			})
			break;
	}
}

/**
 * webview方式打开网页
 * @param url 
 */
export const openWebView = (params: UniApp.NavigateToOptions) => {
	uni.navigateTo(params)
}

/**
 * 显示消息框
 * @param message 
 * @param options 
 */
export const message = (message: string, options?: any) => {
	options = {
		title: message,
		icon: 'none',
		...options
	}
	uni.showToast(options)
}
/**
 * 生成订单表单ID（防止循环内容不生效）
 * @returns 
 */
export const orderId = () => {
	const rand = Math.random() * 100;
	const id = Date.now() + rand;
	return id;
}

/**
 * 获取时间格式数据
 * @param type 
 * @returns 
 */
export const getDate = (type: string) => {
	const date = new Date();
	if (type === 'start') {
		date.setDate(date.getDate() + 3)
	} else if (type === 'end') {
		date.setFullYear(date.getFullYear() + 1)
	}
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	const dateString = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

	return dateString;
}

// 检测是否在微信浏览器
export const isWeiXinLogin = () => {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true; // 微信中打开
	} else {
		return false; // 普通浏览器中打开
	}
}
export const getQuery = (path: string, name: string) => {
	var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
	if (reg.test(path))
		return unescape(RegExp.$2.replace(/\+/g, " "));
	return "";
}
/**
 * 替换地址栏#参数不跳转
 * @param key 参数名
 * @param value 参数值
 * @returns void
 * @example replaceUrlParam('key','value')
 */
export function replaceUrlParam(key: string, value: string): void {
    const url = new URL(globalThis.location.href);
	const queryArr=url.hash.split('?');
	const hashParams = new URLSearchParams(queryArr[1]??''); // 获取hash中的参数
    // 设置新的参数值
    hashParams.set(key, value);
    // 更新hash
    url.hash = queryArr[0]+'?'+hashParams.toString();
    globalThis.history.replaceState({}, '', url.href);
}
/**
 * 删除地址栏#参数不跳转
 * @param key 
 */
export const delUrlParam = (key: string) => {
    const url = new URL(globalThis.location.href);
	const queryArr=url.hash.split('?');
	const hashParams = new URLSearchParams(queryArr[1] ?? ''); // 获取hash中的参数
	// 删除参数
	hashParams.delete(key);
	// 更新hash
	url.hash = queryArr[0]+'?'+hashParams.toString();
	globalThis.history.replaceState({}, '', url.href);
}
/**
 * 批量替换地址栏#参数不跳转
 * @param params 参数对象
 * @returns void
 * @example replaceUrlParams({key1:'value1',key2:'value2'})
 */
export function replaceUrlParams(params: Record<string, string>): void {
	const url = new URL(globalThis.location.href);
	const queryArr=url.hash.split('?');
	const hashParams = new URLSearchParams(queryArr[1]??''); // 获取hash中的参数
	// 设置新的参数值
	for(let x in params){
		hashParams.set(x, params[x]);
	}
	// 更新hash
	url.hash = queryArr[0]+'?'+hashParams.toString();
	globalThis.history.replaceState({}, '', url.href);
}